/**
 * 获取url参数
 * ======================================================
 * 使用示例
 * let params=getUrlParams();
 *  获取ID值:params['id']
 * ======================================================
 */
import { Message } from 'element-ui';
import { getPublicPath } from '@/utils/publicPath';
import { requestData } from '@/api';
export function getUrlParams(query) {
  const url = location.search; // 获取url中'?'符后的字串
  const theRequest = {};
  if (url.indexOf('?') !== -1) {
    const str = url.substr(1);
    const strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
    }
  }
  if (query !== true) {
    const pos = location.hash.indexOf('?');
    if (pos !== -1) {
      const paramStr = location.hash.substr(pos + 1);
      const vars = paramStr.split('&');
      for (let i = 0; i < vars.length; i++) {
        var par = vars[i].split('=');
        if (par[0] === 'sys') {
          theRequest.systemType = par[1];
          break;
        }
      }
    }
  }
  return theRequest;
}
export function getHashParams() {
  const url = location.hash.split('?')[1]; // 获取hush中'?'符后的字串
  const theRequest = {};
  if (url) {
    const strs = url.split('&');
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
    }
  }
  return theRequest;
}
/**
  * 获取url参数
  * ======================================================
  * 使用示例
  * let params=getRouteParams(url);
  *  获取ID值:params['id']
  * ======================================================
  */
export function getRouteParams(url) {
  const theRequest = {};
  if (!isEmpty(url)) {
    const strs = url.split('&');
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
    }
  }

  return theRequest;
}

/**
  * 判断是否为空
  */
export function isEmpty(val) {
  return (
    val === null ||
     typeof val === 'undefined' ||
     (typeof val === 'string' && val === '' && val !== 'undefined') ||
     val === '[]'
  );
}

/**
  * 时间格式化
  * ======================================================
  * 使用示例
  * let datetime=formatDate(date, "yyyy-MM-dd hh:mm");
  * ======================================================
  */
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + '';
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

/* 下载方法 */
function downFile(blob, fileName) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  }
}
/**
  * 导出文件
  */
export function exportFile(data, filaename) {
  const blob = new Blob([data], { type: 'application/msword' });
  downFile(blob, filaename);
}

/**
  * 增减天数
  */
export function addDate(date, days) {
  if (isEmpty(days)) {
    days = 1;
  }
  let currDate = date.replace(/-/g, '/');

  // 兼容IE, new Date() 不支持年月
  if (currDate.indexOf('/') !== -1 && currDate.split('/').length === 2) {
    currDate = currDate + '/1';
  }
  var newdate = new Date(currDate);
  newdate.setDate(newdate.getDate() + days);
  // newdate = new Date(newdate);
  // var m = newdate.getMonth() + 1;
  // var d = newdate.getDate();
  return formatDate(newdate, 'yyyy-MM-dd');
  // return newdate.getFullYear() + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}
/**
  * 增减小时
  */
export function addHours(date, hours) {
  if (isEmpty(hours)) {
    hours = 1;
  }
  var newdate = new Date(date.replace(/-/g, '/'));
  newdate.setHours(newdate.getHours() + hours);
  newdate.setSeconds(newdate.getSeconds() - 1); // 多减去一秒
  return formatDate(newdate, 'yyyy-MM-dd hh:mm:ss');
  // return newdate.getFullYear() + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + (h < 10 ? ('0' + h) : h);
}

/**
  * 增减月份
  */
export function addMonth(date, months) {
  if (isEmpty(months)) {
    months = 1;
  }
  let currDate = date.replace(/-/g, '/');

  // 兼容IE, new Date() 不支持年月
  if (currDate.indexOf('/') !== -1 && currDate.split('/').length === 2) {
    currDate = currDate + '/1';
  }
  var newdate = new Date(currDate);
  newdate.setMonth(newdate.getMonth() + months);
  var m = newdate.getMonth() + 1;
  return newdate.getFullYear() + '-' + (m < 10 ? '0' + m : m);
}

/**
  * 增减年份
  */
export function addYear(date, years) {
  if (isEmpty(years)) {
    years = 1;
  }
  var newdate = new Date(date.replace(/-/g, '/'));
  newdate.setFullYear(newdate.getFullYear() + years);
  return newdate.getFullYear();
}

/**
  * 通过时间查出当前周的起始时间
  */
export function getWeek(date) {
  const nowDayOfWeek = date.getDay(); // 今天本周的第几天
  const nowDay = date.getDate(); // 当前日
  // const nowMonth = date.getMonth() + 1;; // 当前月
  // 上面的是下一个月的，这个才是当前月
  const nowMonth = date.getMonth();
  const nowYear = date.getFullYear();
  const weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
  const weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
  return [
    formatDate(weekStartDate, 'yyyy-MM-dd'),
    formatDate(weekEndDate, 'yyyy-MM-dd')
  ];
}

/**
  * 排序
  */
// 升序
export function compare(property) {
  return function(a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  };
}
// 降序
export const compareDown = property => {
  return function(a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value2 - value1;
  };
};

/**
  * echart悬浮框位置
  */
export function tipPosition(point, size) {
  // 其中point为当前鼠标的位置
  let y = '5%';
  if (size.contentSize[1] < size.viewSize[1]) {
    y = point[1];
    if (size.viewSize[1] < size.contentSize[1] + point[1]) {
      y = size.viewSize[1] - size.contentSize[1];
    }
  }
  if (point[0] > 220) {
    return [point[0] - 220, y];
  } else {
    return [point[0] + 50, y];
  }
}

/**
  * 获取中英文等字符串长度
  */
export function getStrLen(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var a = str.charAt(i);
    if (a.match(/[^\x00-\xff]/gi) != null) {
      len += 16;
    } else if (/[a-z]/.test(i)) {
      len += 10;
    } else if (/[A-Z]/.test(i)) {
      len += 16;
    } else {
      len += 10;
    }
  }
  return len;
}

/**
  * 判断time1是否大于time2 false是大于 true为不大于
  */
export function compareTime(time1, time2) {
  var date1 = new Date(time1.replace(/-/g, '/'));
  var date2 = new Date(time2.replace(/-/g, '/'));
  var times = date1.getTime() - date2.getTime();
  if (times > 0) {
    return false;
  }
  return true;
}

// 深拷贝
export const deepClone = o => {
  if (o instanceof Array) {
    const n = [];
    for (let i = 0; i < o.length; ++i) {
      n[i] = deepClone(o[i]);
    }
    return n;
  } else if (o instanceof Function) {
    const n = new Function('return ' + o.toString())();
    return n;
  } else if (o instanceof Object) {
    const n = {};
    for (const i in o) {
      n[i] = deepClone(o[i]);
    }
    return n;
  } else {
    return o;
  }
};
// 浅拷贝
export const clone = o => {
  const obj = {};
  for (const keys in o) {
    if (o.hasOwnProperty(keys)) {
      obj[keys] = o[keys];
    }
  }
  return obj;
};

// 数组对象去重,根据key值
export const unique = (arr, key) => {
  var obj = {};
  return arr.reduce((item, next) => {
    obj[next[key]] ? '' : (obj[next[key]] = true && item.push(next));
    return item;
  }, []);
};

// 打开系统页面
export const openSystem = (menu, flag) => {
  localStorage.setItem('menuCode' + menu.menuCode, menu.menuName);
  localStorage.removeItem('menus' + menu.menuCode);
  const target = flag ? '_self' : '_blank';
  /**
    * 系统桌面菜单打开逻辑
    * 如果新系统（menuNewUrl）为空，则打开老系统menuUrl配置的地址
    * 如果新系统（menuNewUrl）不为空，则直接打开系统menuNewUrl配置的地址
    * 优先级： menuNewUrl > menuUrl
    */
  if (isEmpty(menu.menuNewUrl)) {
    if (isEmpty(menu.menuUrl)) {
      Message({
        message:
           '未找到链接地址，请联系管理员进行相关配置！',
        type: 'warning'
      });
    } else {
      window.open(menu.menuUrl, target);
    }
  } else {
    window.open(
      getPublicPath() +
       menu.menuNewUrl +
       '/index.html?systemType=' +
       menu.menuCode,
      target
    );
  }
};

/**
  * 获取桌面菜单以及系统导航菜单
  */

export const getDeskTop = () => {
  const data = JSON.parse(localStorage.getItem('deskTopData'));
  // 去重取出父级元素
  const parentIds = [];
  const deskTopData = [];
  if (Array.isArray(data)) {
    data.forEach(item => {
      if (parentIds.length) {
        if (parentIds.indexOf(item.sType) === -1) {
          // 如果不相等
          deskTopData.push({
            sType: item.sType,
            sTypeName: item.sTypeName,
            children: [item]
          });
          parentIds.push(item.sType);
        } else {
          // 如果相等
          const some = deskTopData.filter(k => k.sType === item.sType);
          some[0].children.push(item);
        }
      } else {
        deskTopData.push({
          sType: item.sType,
          sTypeName: item.sTypeName,
          children: [item]
        });
        parentIds.push(item.sType);
      }
    });
  }
  return { parentIds, deskTopData };
};

/**
  * 获取登录用户名称
  */
export const getUserName = () => {
  return new Promise((resolve, reject) => {
    if (localStorage.getItem('user-Info') == null) {
      const httpOptions = { url: '/bfs/user/info/get', type: 'post' };
      requestData(httpOptions).then(data => {
        resolve(data.data.username);
        localStorage.setItem('user-Info', JSON.stringify(data.data));
      });
    } else {
      const userInfo = localStorage.getItem('user-Info');
      resolve(JSON.parse(userInfo).username);
    }

    // const userInfo = localStorage.getItem('user-Info');
    // resolve(JSON.parse(userInfo).username);
  });
};
/**
  * 用于将一个或多个对象的内容合并到目标对象
  * @param {boolean} deep --指示是否深度合并对象，默认为false。如果该值为true，且多个对象的某个同名属性也都是对象，则该"属性对象"的属性也将进行合并。
  * @param {Object} target  --目标对象，其他对象的成员属性将被附加到该对象上。
  * @param {Object} options --Object类型 第一个被合并的对象
  */
export const extend = (deep, target, options) => {
  let copyIsArray;
  const toString = Object.prototype.toString;
  const hasOwn = Object.prototype.hasOwnProperty;
  const class2type = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Object]': 'object'
  };
  const type = function(obj) {
    return obj == null
      ? String(obj)
      : class2type[toString.call(obj)] || 'object';
  };
  const isWindow = function(obj) {
    return obj && typeof obj === 'object' && 'setInterval' in obj;
  };
  const isArray =
     Array.isArray ||
     function(obj) {
       return type(obj) === 'array';
     };
  const isPlainObject = function(obj) {
    if (!obj || type(obj) !== 'object' || obj.nodeType || isWindow(obj)) {
      return false;
    }
    if (
      obj.constructor &&
       !hasOwn.call(obj, 'constructor') &&
       !hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')
    ) {
      return false;
    }
    let key;
    for (key in obj) {
      continue;
    }
    return key === undefined || hasOwn.call(obj, key);
  };
  for (const name in options) {
    const src = target[name];
    const copy = options[name];
    if (target === copy) {
      continue;
    }
    if (
      deep &&
       copy &&
       (isPlainObject(copy) || (copyIsArray = isArray(copy)))
    ) {
      let clone;
      if (copyIsArray) {
        copyIsArray = false;
        clone = src && isArray(src) ? src : [];
      } else {
        clone = src && isPlainObject(src) ? src : {};
      }
      target[name] = extend(deep, clone, copy);
    } else if (copy !== undefined) {
      target[name] = copy;
    }
  }
  return target;
};

/**
  * 数字转换成罗马数字
  */
export const translateRoman = num => {
  var newArr = [];
  var newStr;
  num = Number(num);
  // 先把数字转化为相应的罗马字母
  while (num > 0) {
    if (num - 1000 >= 0) {
      newArr.push('M');
      num -= 1000;
    } else if (num - 500 >= 0) {
      newArr.push('D');
      num -= 500;
    } else if (num - 100 >= 0) {
      newArr.push('C');
      num -= 100;
    } else if (num - 50 >= 0) {
      newArr.push('L');
      num -= 50;
    } else if (num - 10 >= 0) {
      newArr.push('X');
      num -= 10;
    } else if (num - 5 >= 0) {
      newArr.push('V');
      num -= 5;
    } else if (num - 1 >= 0) {
      newArr.push('I');
      num -= 1;
    }
  }
  newStr = newArr.join('');
  // 将4和9的情况进行替换
  newStr = newStr.replace(/VI{4}|LX{4}|DC{4}|I{4}|X{4}|C{4}/g, function(match) {
    switch (match) {
      case 'VIIII':
        return 'IX';
      case 'LXXXX':
        return 'XC';
      case 'DCCCC':
        return 'CM';
      case 'IIII':
        return 'IV';
      case 'XXXX':
        return 'XL';
      case 'CCCC':
        return 'CD';
    }
  });
  return newStr === 'VI' ? '劣V' : newStr;
};
// 目前是0断面1湖泊
export const translate = num => {
  const type = ['string', 'number'];
  if (type.indexOf(typeof num) === -1) {
    throw new Error(`arguments num expected ${type}, got ${typeof num}`);
  }
  switch (Number(num)) {
    case 0:
      return '河流断面';
    case 1:
      return '湖泊';
  }
};
export const getMd5FilePath = filePath => {
  if (process.env.NODE_ENV === 'production') {
    const files = process.env.md5Map.filter(item => {
      return (
        filePath === item.filePath + '/' + item.fileName + item.extensionName
      );
    });
    if (files.length > 0) {
      return files[0].filePath + '/' + files[0].md5FileName;
    }
  }
  return filePath;
};

/**
  * 获取请求数据
  * params 请求参数             object
  * successMessage 成功提示信息  string
  * rejectMessage 失败提示信息   string
  */

export function getRequestData(params, successMessage, rejectMessage) {
  return new Promise((resolve, reject) => {
    requestData(params).then(res => {
      const { result, message } = res;
      if (result) {
        if (!isEmpty(successMessage)) {
          Message({
            type: 'success',
            message: successMessage
          });
        }
        resolve(res);
      } else {
        reject({ result: false });
        Message({
          type: 'error',
          message: rejectMessage || message
        });
      }
    });
  });
}
/**
  * 上传文件时判断
  * file 文件信息 string
  * type 文件类型 array
  * size 文件大小 number
  */
export function uploadFileHandel(file, type, size) {
  const fileName = file.name.split('.'); // 文件
  const suffixName = fileName[fileName.length - 1];
  if (!type.includes(suffixName)) {
    Message({
      message:
         `上传模板只能是${type.toString()}文件格式!`,
      type: 'warning'
    });
    return false;
  }
  const isLt = file.size / 1024 / 1024 < size;
  if (!isLt) {
    Message({
      message: `上传模板大小不能超过 ${size}MB!`,
      type: 'warning'
    });
    return false;
  }
  const fd = new FormData();
  fd.append('file', file);
  console.log(fd);
  return true;
}
/**
  * 设置密码加密
  */
export const setPwEncrypted = {
  encryptionNum: '', // 加密指数
  encryptionRatio: '', // 加密系数
  // 获取公钥信息
  getRaskey() {
    const opt = {
      url: '/bfs/user/raskey',
      type: 'post',
      params: ''
    };
    return new Promise((resolve, reject) => {
      getRequestData(opt).then(resp => {
        if (resp.result) {
          resolve({ encryptionNum: resp.data.ee, encryptionRatio: resp.data.mm });
        } else {
          Message.error('加密秘钥获取失败，请联系管理员！');
          reject(false);
        }
      });
    });
  },
  // 加密数据
  encryptedString(paramStr) {
    setMaxDigits(130);
    // 第一个参数为加密指数、第二个参数为解密参数、第三个参数为加密系数
    const key = new RSAKeyPair(setPwEncrypted.encryptionNum, '', setPwEncrypted.encryptionRatio);
    // 返回加密后的字符串
    return encryptedString(key, encodeURIComponent(paramStr));
  },
  // 加密过程
  encryptedPreprocess(loginPwd, confirmPWd) {
    return new Promise((resolve, reject) => {
      setPwEncrypted.getRaskey().then((res) => {
        setPwEncrypted.encryptionNum = res.encryptionNum;
        setPwEncrypted.encryptionRatio = res.encryptionRatio;
        let newPwd = '';
        const loginPwdLength = loginPwd.length;
        let i = 7;
        while (i <= loginPwdLength) {
          if (i <= 7) {
            newPwd += setPwEncrypted.encryptedString(loginPwd.substring(0, i));
          } else if (i <= 14) {
            newPwd += setPwEncrypted.encryptedString(loginPwd.substring(7, i));
          } else if (i <= 16) {
            newPwd += setPwEncrypted.encryptedString(loginPwd.substring(14, i));
          }
          if (loginPwdLength - i > 0) {
            i = i + (loginPwdLength - i);
          } else {
            break;
          }
          newPwd += ',';
        }

        const confirmPWdLength = confirmPWd.length;
        let newConfPwd = '';
        i = 7;
        while (i <= confirmPWdLength) {
          if (i <= 7) {
            newConfPwd += setPwEncrypted.encryptedString(confirmPWd.substring(0, i));
          } else if (i <= 14) {
            newConfPwd += setPwEncrypted.encryptedString(confirmPWd.substring(7, i));
          } else if (i <= 16) {
            newConfPwd += setPwEncrypted.encryptedString(confirmPWd.substring(14, i));
          }
          if (confirmPWdLength - i > 0) {
            i = i + (loginPwdLength - i);
          } else {
            break;
          }
          newConfPwd += ',';
        }
        resolve({ newPwd: newPwd, newConfPwd: newConfPwd });
      }, () => { // 获取公钥失败，直接返回未加密的登录密码和确认密码
        reject({ newPwd: loginPwd, newConfPwd: confirmPWd });
      });
    });
  }

};

// 获取服务地址
export function getLocalhostPath() {
  const curWwwPath = window.document.location.href;
  const pathName = window.document.location.pathname;
  const pos = curWwwPath.indexOf(pathName);
  const localhostPath = curWwwPath.substring(0, pos);
  return localhostPath;
}

export const getDict = id => {
  return new Promise((resolve, reject) => {
    const params = {
      url: `/service-base/category/list/${id}`,
      type: 'get',
      params: {}
    };
    requestData(params).then(resp => {
      const { data, success } = resp;
      if (success) {
        resolve(data.data);
      }
    });
  });
};

export const MapLoader = key => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap);
    } else {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src =
       `https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.DistrictSearch,AMap.MouseTool,AMap.MarkerClusterer,AMap.Geocoder,AMap.PlaceSearch,AMap.AutoComplete,AMap.PolygonEditor,AMap.GeoJSON&callback=initAMap`;
      script.onerror = reject;
      document.head.appendChild(script);
    }
    window.initAMap = () => {
      resolve(window.AMap);
    };
  });
};

export const AMapUILoader = () => {
  return new Promise((resolve, reject) => {
    if (window.AMapUI) {
      resolve(window.AMapUI);
    } else {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src =
       'http://webapi.amap.com/ui/1.1/main.js?v=1.1.1';
      script.onerror = reject;
      document.head.appendChild(script);
      script.onload = () => {
        resolve(window.AMapUI);
      };
    }
  });
};

/**
        * 密码加密
        * @param {String} password   -密码
        * @returns {String}          -返回加密后的密码
        */
export const doSM3 = (password) => {
  // /** eslint-disable */
  let msgData = window.CryptoJS.enc.Utf8.parse(password);
  const sm3keycur = new window.SM3Digest();
  msgData = sm3keycur.GetWords(msgData.toString());
  sm3keycur.BlockUpdate(msgData, 0, msgData.length);
  const c3 = new Array(32);
  sm3keycur.DoFinal(c3, 0);
  const hashHex = sm3keycur.GetHex(c3).toString();
  return hashHex.toUpperCase();
};

